package com.umeox.mediaplayer

import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.os.Environment
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yc.music.model.AudioBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.util.*
import java.util.concurrent.TimeUnit

class MusicViewModel : ViewModel() {
    var TAG = "MusicViewModel"
    private var musicMutableLiveData = MutableLiveData<MutableList<AudioBean>>()
    val musicLiveData: LiveData<MutableList<AudioBean>> = musicMutableLiveData

    private var movieMutableLiveData = MutableLiveData<MutableList<MovieBean>>()
    val movieLiveData: LiveData<MutableList<MovieBean>> = movieMutableLiveData


    private var musicBeanList = mutableListOf<AudioBean>()
    private var movieBeanList = mutableListOf<MovieBean>()

    fun getMusicList() {
        musicBeanList.clear()
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val movies = File(Environment.getExternalStorageDirectory(), "music")
                val files = movies.listFiles()?.filter { it.isFile && it.name.endsWith(".mp3") }

                if (files != null) {
                    if (files.isNotEmpty()) {
                        files.forEach {
                            val retriever = MediaMetadataRetriever()
                            val filePath = it.absolutePath
                            retriever.setDataSource(filePath)

                            val durations =
                                retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
                            var aLong = durations!!.toLong()

                            musicBeanList.add(AudioBean().apply {

                                path = filePath
                                album =
                                    retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM)
                                artist =
                                    retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)
                                        ?: ""
                                title =
                                    (retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)
                                        ?: it.name).replace(".mp3","")
                                Log.d(TAG, "setupMovieBeanList: $artist album:$album title:$title")
                                val hour: String = getFormat(TimeUnit.MILLISECONDS.toHours(aLong))
                                aLong %= TimeUnit.HOURS.toMillis(1)
                                val minute: String =
                                    getFormat(TimeUnit.MILLISECONDS.toMinutes(aLong))
                                aLong %= TimeUnit.MINUTES.toMillis(1)
                                val seconds: String =
                                    getFormat(TimeUnit.MILLISECONDS.toSeconds(aLong))
                                duration = durations.toLong()
                                totalDuration = if (hour == "00") String.format(
                                    "%s:%s",
                                    minute,
                                    seconds
                                ) else String.format("%s:%s:%s", hour, minute, seconds)
                            })
                            musicBeanList.forEach { audio ->
                                audio.id = audio.hashCode().toString()
                            }

                        }
                    }

                }

            }
            musicMutableLiveData.value = musicBeanList
        }
    }

    fun getMusicTestList() {
        musicBeanList.clear()
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                musicBeanList.add(AudioBean().apply {

                    path = "https://res.weixiaobao.com/audio/009.mp3"
                    title = "test"
                })
                musicBeanList.forEach { audio ->
                    audio.id = audio.hashCode().toString()
                }

            }
            musicMutableLiveData.value = musicBeanList
        }
    }


    fun getMovieList() {
        movieBeanList.clear()
        viewModelScope.launch {

            withContext(Dispatchers.IO) {

                val movies = File(Environment.getExternalStorageDirectory(), "movies")
                val files = movies.listFiles()?.filter { it.isFile && it.name.endsWith(".mp4") }
                Log.d(TAG, "getMovieList: ${files?.size}")
                if (files != null) {
                    if (files.isNotEmpty()) {
                        files.forEach {
                            val retriever = MediaMetadataRetriever()
                            val filePath = it.absolutePath
                            retriever.setDataSource(filePath)

                            val bitmap = retriever.getFrameAtTime(1)

                            val durations =
                                retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
                            var aLong = if (durations.isNullOrEmpty()) 0 else durations.toLong()

                            val hour: String = getFormat(TimeUnit.MILLISECONDS.toHours(aLong))
                            aLong %= TimeUnit.HOURS.toMillis(1)
                            val minute: String = getFormat(TimeUnit.MILLISECONDS.toMinutes(aLong))
                            aLong %= TimeUnit.MINUTES.toMillis(1)
                            val seconds: String = getFormat(TimeUnit.MILLISECONDS.toSeconds(aLong))

                            var duration = if (hour == "00") String.format(
                                "%s:%s",
                                minute,
                                seconds
                            ) else String.format("%s:%s:%s", hour, minute, seconds)

                            movieBeanList.add(
                                MovieBean(
                                    it.name,
                                    it.absolutePath,
                                    duration,
                                    bitmap?.compression()
                                )
                            )

                        }
                    }
                }
            }

            movieMutableLiveData.value = movieBeanList

        }
    }

    private fun getFormat(aLong: Long): String {
        return String.format(Locale.getDefault(), "%02d", aLong)
    }

    private fun Bitmap.compression(): Bitmap? {
        val bitmap = Bitmap.createScaledBitmap(this, 120, 80, false)
        if (!this.isRecycled) {
            this.recycle()
        }
        return bitmap

    }
}